<template>
  <el-dialog
    :title="'分配用户类别'"
    append-to-body
    :close-on-click-modal="false"
    @close="closeDialog()"
    :visible="visible"
    width="600px"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="120px"
    >
      <el-form-item label="用户类别" prop="shopUserType">
        <el-radio-group v-model="dataForm.shopUserType">
          <el-radio label="2" border>普通用户</el-radio>
          <el-radio label="3" border>销售代表</el-radio>
        </el-radio-group>
      </el-form-item>

      <div v-if="dataForm.shopUserType == shopUserTypeEnum.normal">
        <el-form-item label="已关联销售代表" prop="realName" v-if="dataForm.salesUserList.length > 0">
          <div class="avue-crud">
            <el-table :data="dataForm.salesUserList" border>
              <el-table-column
                prop="loginAccount"
                header-align="center"
                align="center"
                label="登录手机号">
              </el-table-column>
              <el-table-column
                prop="nickName"
                header-align="center"
                align="center"
                label="昵称">
              </el-table-column>
              <el-table-column
                prop="realName"
                header-align="center"
                align="center"
                label="真实姓名">
              </el-table-column>
              
              <el-table-column header-align="center" align="center" label="操作">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-edit"
                    @click="handleShowSales(scope.row)"
                    >更换销售代表</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div style="color: #FF0000; font-size: 12px">
            <i class="el-icon-warning"></i>
            <span>关联当前销售代表后，后期该用户产生的订单归当前销售代表所有</span>
          </div>
        </el-form-item>

        <el-form-item label="分配销售代表" prop="realName" v-else>
          <template>
            <el-button
              type="text"
              size="small"
              icon="el-icon-edit"
              @click="handleShowSales()"
              >选择销售代表</el-button>
          </template>
        </el-form-item>
      </div>
      <div v-else-if="dataForm.shopUserType == shopUserTypeEnum.sales">
        <el-form-item label="所属部门" prop="deptId" >
          <avue-input-tree
            v-model="dataForm.deptId"
            :node-click="getNodeData"
            :dic="treeDeptData"
            :props="defaultProps"
            placeholder="请选择所属部门"
            style="width:100%"
          />
        </el-form-item>
        
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-if="canSubmit"
        >确定</el-button
      >
    </span>

    <Sales
        v-if="visibleSales"
        ref="salesForm"
        @selectUserSalesResult="selectUserSalesResult"
        :visible.sync="visibleSales"
      ></Sales>
  </el-dialog>
</template>

<script>
import {getObj, putObj} from '@/api/shop_user/user';
import Sales from '@/components/userDivide/sales.vue';
import { fetchTree } from '@/api/admin/dept'
import {shopUserTypeEnum} from '@/const/const';

export default {
  props:{
    visible: {
      type: Boolean,
      default: false
    },
  },
  data(){
    return{
      shopUserTypeEnum,
      canSubmit: false,
      dataForm: {
        deptId:''
      },
      dataRule:{
        shopUserType: [
          { required: true, message: "用户类别不能为空", trigger: "blur" },
        ],
        deptId: [
          { required: true, message: "所属部门不能为空", trigger: "blur" },
        ]
      },
      visibleSales:false,
      treeDeptData: [],
      defaultProps: {
        label: 'name',
        value: 'id'
      },

      newUserSales:[]
    }
  },
  components:{
    Sales
  },
  watch:{
    'dataForm.shopUserType':function(){
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate();
      });
    }
  },
  methods:{
    /**
     * 初始化
     */
    init(id){
      this.canSubmit = true;
      getObj(id).then(res=>{
        this.dataForm = res.data.data
        this.dataForm.deptId = this.dataForm.deptId ? this.dataForm.deptId : ''
        if(this.dataForm.shopUserType == shopUserTypeEnum.public){
          // 公海用户的场合，清空选择项
          this.dataForm.shopUserType = ''
        }
      })

      // 获取部门列表
      fetchTree().then(response => {
        this.treeDeptData = response.data.data
      })
      
    },

    /**
     * 显示销售代表列表
     */
    handleShowSales(){
      this.visibleSales = true
      this.$nextTick(() => {
        this.$refs.salesForm.init(this.dataForm.id);
      });
    },

    //重置表单
    closeDialog() {
      this.$emit('update:visible', false)
    },

    /**
     * 提交
     */
    dataFormSubmit(){
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.canSubmit = false;
          debugger
          let data = {}
          data.id = this.dataForm.id
          data.shopUserType = this.dataForm.shopUserType
          
          if(this.dataForm.shopUserType == shopUserTypeEnum.normal){
            // 普通用户的场合
            if(this.dataForm.salesUserList.length <= 0){
              this.$message.error("请选择销售代表")
              return
            } else {
              data.salesShopUserId = this.dataForm.salesUserList[0].id
            }
            data.deptId = ''
          } else {
            // 销售代表的场合
            data.deptId = this.dataForm.deptId
            // 销售代表默认自己
            data.salesShopUserId = data.id
          }
          putObj(data).then(res=>{
            this.$notify.success('修改成功')
            this.$emit("refreshDataList");
            this.closeDialog()
          })
        }
      });
    },

    getDataList(){

    },

    getNodeData(){

    },

    /**
     * 选择销售代表
     */
    selectUserSalesResult(data){
      this.dataForm.salesUserList = []
      this.dataForm.salesUserList.push(data)
    }
  }
}
</script>
